package com.lu.base.tools.thread;

import android.util.Log;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * author: luqihua
 * date:2019-09-26
 * description: 线程工厂 捕获线程异常
 **/
public class CustomThreadFactory implements ThreadFactory {
    private final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private static final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public final Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {

        private static final String TAG = "UncaughtException";

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            final String errorMsg = "线程池异常：" + t.getName() + "::" + e.getMessage();
            Log.e(TAG, errorMsg, e);
        }
    };

    private static class HOLDER {
        private static final CustomThreadFactory sInstance = new CustomThreadFactory("Default");
    }

    public static CustomThreadFactory getDefault() {
        return HOLDER.sInstance;
    }

    public CustomThreadFactory(String threadTag) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = threadTag +
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        //错误处理
        t.setUncaughtExceptionHandler(exceptionHandler);
        return t;
    }

    /**
     * 创建一个线程执行任务
     *
     * @param runnable
     */
    public void executeSimple(String tag, Runnable runnable) {
        Thread thread = newThread(runnable);
        thread.setName(tag + "-" + thread.getName());
        thread.start();
    }
}
